<?php

namespace App\Http\Controllers\V1;

use App\Http\Controllers\ApiBaseController;
use App\Models\BalanceLog;
use App\Models\ChannelGroup;
use App\Models\ChannelGroupItem;
use App\Models\ChannelProduct;
use App\Models\CustomerProduct;
use App\Models\CustomerProductChannel;
use App\Models\CzOrder;
use App\Models\CzOrderQueue;
use App\Models\CzProduct;
use App\Models\CzProductBlack;
use App\Models\CzSpec;
use App\Models\InsertOrderSn;
use App\Models\ProductLimit;
use App\Models\SysDictData;
use App\Models\SysUser;
use App\Models\UserGroupProduct;
use App\Models\UserGroupProductChannel;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class MobiController extends ApiBaseController
{
    public function getProductByMobile(Request $request)
    {
        $params = $request->all();
        $mobile = $params['mobile'] ?? '';
        if (!is_numeric($mobile)) {
            return error('手机号码格式有误');
        }
        $mobile_pref = substr($mobile, 0, 7);

        $isp_name = "";
        $city_id = 0;
        $is_trans = 0;

        // $province = "";
        // $city = "";

        //获取号码归属地
        $mobile_info = DB::table('phone')->where('phone', $mobile_pref)->first();
        // $is_trans = 0;
        if (!$mobile_info) {
            logger('请求接口');
            // return error('获取归属地失败');
            // 查询归属地
            $areaValidate = $this->validateMobile($mobile);
            if ($areaValidate['code'] == 200) {
                $is_trans = $areaValidate['is_trans'];

                if (!$areaValidate['is_has']) {
                    // 携号转网入库
                    DB::table('mobile_is_trans')->insert([
                        "mobile" => $mobile,
                        "created_at" => time(),
                        "updated_at" => time(),
                    ]);
                }

                if ($areaValidate['area']) {
                    $area_arr = explode('-', $areaValidate['area']);
                    $province = $area_arr[0];
                    $city = $area_arr[1];
                    $isp_name = $areaValidate['isp'];
                    // 获取area_code
                    $new_area_info = DB::table('areas')->where('province_short_name', $province)->where('city_short_name', $city)->first();
                    $city_id = $new_area_info->id;
                    // var_dump($areaValidate);
                    // 保存至数据库
                    DB::table('phone')->insert([
                        "pref" => substr($mobile, 0, 3),
                        "phone" => substr($mobile, 0, 7),
                        "province" => $province,
                        "city" => $city,
                        "isp" => $isp_name,
                        "post_code" => $new_area_info->zip_code,
                        "city_code" => $new_area_info->city_code,
                        "area_code" => $city_id,
                    ]);
                } else {
                    // 这种情况是三方没有返回地区
                    return error('获取归属地失败');
                }
                if ($is_trans) {
                    return error('携号转网无法充值');
                }
            } else {
                return error('获取归属地失败');
            }
        } else {
            logger('查询数据库');

            $city_id = $mobile_info->area_code;
            $isp_name = $mobile_info->isp;
            // $province = $mobile_info->province;
            // $city = $mobile_info->city;
        }



        // if($this->validateMobileIsBlank($mobile_info)){
        //     return error('')''
        // }
        //20220424 预防多个城市id的数据
        if (strpos($city_id, '/') !== false) {
            $city_id_exp = explode("/", $city_id);
            $city_id = $city_id_exp[0];
        }


        $isp = 0;
        switch ($isp_name) {
            case '移动':
                $isp = 1;
                break;
            case '联通':
                $isp = 2;
                break;
            case '电信':
                $isp = 3;
                break;
        }
        $area_info = DB::table('areas')->where('id', $city_id)->first();
        if (!$area_info) {
            return error('地区信息不存在');
        }
        $province_id = $area_info->parent_id;

        //获取用户全部产品
        $user_id = auth()->id();
        $user = SysUser::find($user_id);
        $user_spec_id = [0];
        if ($user->group_id > 0) {
            $user_spec_id = UserGroupProduct::filter(
                [
                    'user_group_id' => $user->group_id,
                    'isp' => $isp
                ]
            )->pluck('spec_id');
        } else {
            $user_spec_id = CustomerProduct::filter(
                [
                    'user_id' => $user->id,
                    'isp' => $isp
                ]
            )->pluck('spec_id');
        }


        //获取产品
        $product_list = CzProduct::with([
            'specs' => function ($query) {
                $query->where('status', 1);
            }
        ])->filter([
            'mobi_province_id' => $province_id,
            'mobi_city_id' => $city_id,
            'mobi_spec_id' => $user_spec_id,
            'isp' => $isp
        ])
            ->get();


        return success(['data' => $product_list]);
    }

    public function getProductByIsp(Request $request)
    {
        $params = $request->all();
        $isp = $params['isp'] ?? 0;
        if (!is_numeric($isp)) {
            return error('请选择运营商');
        }

        //获取用户全部产品
        $user_id = auth()->id();
        $user = SysUser::find($user_id);
        $user_spec_id = [0];
        if ($user->group_id > 0) {
            $user_spec_id = UserGroupProduct::filter(
                [
                    'user_group_id' => $user->group_id,
                    'isp' => $isp
                ]
            )->pluck('spec_id');
            $user_all_price = UserGroupProduct::filter([
                'user_group_id' => $user->group_id,
                'isp' => $isp
            ])->select('spec_id', 'user_group_price as user_price')->get();
        } else {
            $user_spec_id = CustomerProduct::filter(
                [
                    'user_id' => $user->id,
                    'isp' => $isp
                ]
            )->pluck('spec_id');
            $user_all_price = CustomerProduct::filter([
                'user_id' => $user->id,
                'isp' => $isp
            ])->select('spec_id', 'user_price')->get();
        }

        if ($user_all_price) {
            $user_all_price = $user_all_price->toArray();
            $user_all_price = convert_arr_key($user_all_price, 'spec_id');
        }
        //获取产品
        $product_list = CzProduct::with([
            'specs' => function ($query) use ($user_spec_id) {
                $query->whereIn('id', $user_spec_id)->where('status', 1);
            }
        ])->filter([
            'mobi_spec_id' => $user_spec_id,
            'isp' => $isp
        ])
            ->get();

        if ($product_list) {
            $product_list = $product_list->toArray();
            foreach ($product_list as $k1 => $product) {
                foreach ($product['specs'] as $k2 => $spec) {
                    $product_list[$k1]['specs'][$k2]['user_price'] = $user_all_price[$spec['id']]['user_price'];
                    // if (isset($user_all_price[$spec['id']])) {

                    // }
                }
            }
        }

        return success(['data' => $product_list]);
    }

    public function recharge(Request $request)
    {
        $params = $request->all();
        $mobile = $params['mobile'] ?? '';
        $password = $params['password'] ?? '';
        $product_id = $params['product_id'] ?? 0;
        $spec_id = $params['spec_id'] ?? 0;
        $batch_order_sn = $params['batch_order_sn'] ?? '';
        $user_order_sn = $params['user_order_sn'] ?? '';
        $user = auth()->user();
        // 验证密码
        if (Hash::check($request->post('password'), $user->password) == false) {
            return error('密码不匹配');
        }
        if (!is_numeric($mobile)) {
            return error('手机号码格式有误');
        }
        // 20220527
        if ($this->validateMobileIsBlank($mobile)) {
            return error('号码' . $mobile . '为黑名单号码');
        }
        $mobile_pref = substr($mobile, 0, 7);

        $isp_name = "";
        $city_id = 0;
        $province = "";
        $city = "";
        $is_trans = 0;

        //获取号码归属地
        $mobile_info = DB::table('phone')->where('phone', $mobile_pref)->first();
        if (!$mobile_info) {
            // return error('获取归属地失败');
            // 查询归属地
            $areaValidate = $this->validateMobile($mobile);
            if ($areaValidate['code'] == 200) {
                $is_trans = $areaValidate['is_trans'];

                if (!$areaValidate['is_has']) {
                    // 携号转网入库
                    DB::table('mobile_is_trans')->insert([
                        "mobile" => $mobile,
                        "created_at" => time(),
                        "updated_at" => time(),
                    ]);
                }

                if ($areaValidate['area']) {
                    $area_arr = explode('-', $areaValidate['area']);
                    $province = $area_arr[0];
                    $city = $area_arr[1];
                    $isp = $areaValidate['isp'];
                    // 获取area_code
                    $new_area_info = DB::table('areas')->where('province_short_name', $province)->where('city_short_name', $city)->first();
                    $city_id = $new_area_info->id;
                    // 保存至数据库
                    DB::table('phone')->insert([
                        "pref" => substr($mobile, 0, 3),
                        "phone" => substr($mobile, 0, 7),
                        "province" => $province,
                        "city" => $city,
                        "isp" => $isp_name,
                        "post_code" => $new_area_info->zip_code,
                        "city_code" => $new_area_info->city_code,
                        "area_code" => $city_id,
                    ]);
                } else {
                    // 这种情况是三方没有返回地区
                    return error('获取归属地失败');
                }
                if ($is_trans) {
                    return error('携号转网无法充值');
                }
            } else {
                return error('获取归属地失败');
            }
        } else {
            $city_id = $mobile_info->area_code;
            $isp_name = $mobile_info->isp;
            $province = $mobile_info->province;
            $city = $mobile_info->city;
        }




        //20220424 预防多个城市id的数据
        if (strpos($city_id, '/') !== false) {
            $city_id_exp = explode("/", $city_id);
            $city_id = $city_id_exp[0];
        }


        $isp = 0;
        switch ($isp_name) {
            case '移动':
                $isp = 1;
                break;
            case '联通':
                $isp = 2;
                break;
            case '电信':
                $isp = 3;
                break;
        }
        $area_info = DB::table('areas')->where('id', $city_id)->first();
        if (!$area_info) {
            return error('地区信息不存在');
        }
        $province_id = $area_info->parent_id;

        $product_info = CzProduct::with(['productLimit' => function ($q) {
            $q->where('status', 1);
        }])->where('id', $product_id)->first();
        if (!$product_info) {
            return error('产品不存在');
        }
        if ($product_info->status == 0) {
            return error('产品已下架');
        }
        /*
        if($product_info->isp !== $isp){
            return error('号码与运营商不符合');
        }
        */
        if ($product_info['province_id'] > 0 && $province_id != $product_info['province_id']) {
            return error('号码归属省份与产品不匹配');
        }
        if ($product_info['city_id'] > 0 && $city_id != $product_info['city_id']) {
            return error('号码归属城市与产品不匹配');
        }
        $spec_info = CzSpec::where('id', $spec_id)->where('product_id', $product_id)->first();
        if (!$spec_info) {
            return error('面值不存在');
        }
        if ($spec_info->status == 0) {
            return error('面值已下架');
        }
        $old_title = $product_info->title . $spec_info->face_value;

        //获取客户产品
        $user_id = auth()->id();
        $user = SysUser::find($user_id);
        // 验证是否有web提交权限
        if (!$user['can_web']) {
            return error('不允许手动提交订单，请联系管理员');
        }
        // 验证限充
        // if ($spec_info->is_limit) {
        if ($product_info->productLimit) {
            // 开启限充，获取限制限充的号码
            //获取限充规则
            $productLimit = ProductLimit::where('product_id', $product_id)->where('status', 1)->first();
            $limit_type = $productLimit->limit_type;
            // logger('limit_type' . $limit_type);
            $limit_value = $productLimit->limit_value;
            $limit_type_value = $productLimit->limit_type_value;
            switch ($limit_type) {
                case 'forever':
                    // 获取用户充值次数
                    $end = "";
                    $start = '';
                    break;
                case 'cur_day':
                    $end = (strtotime(date('Ymd')) + 60 * 60 * 24 - 1);
                    $start = (strtotime(date('Ymd')));
                    break;
                case 'cur_month':
                    $start = strtotime(date('Ym01'));
                    $end = strtotime(date('Ymt')) + 60 * 60 * 24 - 1;
                    break;
                case 'cur_year':
                    $start = strtotime(date("Y-m-d H:i:s", mktime(0, 0, 0, 1, 1, intval(date('Y')))));
                    $end = strtotime(date('Ymd H:i:s'));
                    break;
                case 'hour':
                    // 多少小时内限充
                    $end = strtotime(date('Ymd H:i:s'));
                    $start = $end - $limit_type_value * 3600;
                    break;
                case 'day':
                    $end = strtotime(date('Ymd H:i:s'));
                    $start = $end - $limit_type_value * 3600 * 24;
                    break;
                case 'month':
                    $end = strtotime(date('Ymd H:i:s'));
                    $start = $end - $limit_type_value * 3600 * 24 * 30;  //月算30天
                    break;
                case 'year':
                    $end = strtotime(date('Ymd H:i:s'));
                    $start = $end - $limit_type_value * 3600 * 24 * 365;  //年算365天
                    break;
                case 'time_range':
                    $limit_time = json_decode($productLimit->limit_time, true);
                    $start = intval($limit_time[0] / 1000); //毫秒换秒
                    $end = intval($limit_time[1] / 1000); //毫秒换秒
                    // logger("11" . $start);
                    // logger("22" . $end);
                    break;
                default:
                    break;
            }
            // 产品限充针对product，不针对spec_id
            // updated_at 使用回调成功的时间
            if ($start && $end) {
                $successCount = CzOrder::where('order_status', 3)
                    ->where('mobile', $mobile)
                    ->where('pay_status', 1)
                    ->where('product_id', $product_id)
                    ->whereBetween('updated_at', [$start, $end])
                    ->count();
                $handleCount = CzOrder::whereIn('order_status', [1, 2, 5, 6])
                    ->where('mobile', $mobile)
                    ->where('product_id', $product_id)
                    ->whereBetween('updated_at', [$start, $end])
                    ->count();
            } else {
                // 限制下单不需要添加sys_user_id 为商户,因为产品是针对手机限充
                // 永久
                $successCount = CzOrder::where('order_status', 3)
                    ->where('pay_status', 1)
                    ->where('mobile', $mobile)
                    ->where('product_id', $product_id)
                    ->count();
                $handleCount = CzOrder::whereIn('order_status', [1, 2, 5, 6])
                    ->where('pay_status', 1)
                    ->where('mobile', $mobile)
                    ->where('product_id', $product_id)
                    ->count();
            }
            // storage_log("successCount" . $successCount . "handleCount" . $handleCount);
            // storage_log("limit_value" . $limit_value . "spec_id" . $czSpec->id . "mobile" . $mobile);
            if ($successCount >= $limit_value) {
                return error('当前手机号当前产品被限制充值,请选择其他产品进行充值!');
            }
            if ($successCount + $handleCount >= $limit_value) {
                return error('当前手机号当前产品被限制充值,且已经提交过,耐心等待上一笔充值结果后再提交!');
            }
            // $mobile = $params['mobile'];
            // $productBlackInfo = CzProductBlack::where('spec_id', $spec_id)->where('product_id', $product_id)->where('status', 1)->first();
            // if ($productBlackInfo) {
            //     $is_handing_count = CzOrder::where('mobile', $mobile)->where('spec_id', $spec_id)->where('product_id', $product_id)->whereBetween('created_at', [$spec_info->limit_time, time()])->whereIn('order_status', [1, 2, 5, 6])->count();
            //     // return error($is_handing_count);
            //     if ($is_handing_count >= $productBlackInfo->limit_num) {
            //         return error('当前手机号被限制充值且已经提交过,耐心等待上一笔充值结果后再提交!');
            //     }
            //     $is_success_count = CzOrder::where('mobile', $mobile)->where('order_status', 3)->where('spec_id', $spec_id)->where('product_id', $product_id)->whereBetween('created_at', [$spec_info->limit_time, time()])->count();
            //     if ($is_success_count >= $productBlackInfo->limit_num) {
            //         return error('当前手机号被限制充值!');
            //     }
            //     if ($is_handing_count + $is_success_count >= $productBlackInfo->limit_num) {
            //         return error('当前手机号被限制充值,且已经提交过,耐心等待上一笔充值结果后再提交!');
            //     }
            // }
            // $mobiles = CzProductBlack::where('spec_id', $spec_id)->where('product_id', $product_id)->where('status', 1)->pluck('mobile')->toArray();
            // // 如果开启限充没有配置的话，不做处理
            // if (in_array($mobile, $mobiles)) {
            //     //获取该号码的充值次数
            //     $productBlackInfo = CzProductBlack::where('spec_id', $spec_id)->where('product_id', $product_id)->where('status', 1)->where('mobile', $mobile)->first();
            //     // 1todo bug:一个号码在没有返回成功时可以提交多次 已下单，充值中，失败拦截，压单均判定为处理中
            //     $is_handing_count = CzOrder::where('mobile', $mobile)->whereBetween('created_at', [$spec_info->limit_time, time()])->whereIn('order_status', [1, 2, 5, 6])->count();
            //     if ($is_handing_count == $productBlackInfo->limit_num) {
            //         return error('当前手机号被限制充值且已经提交过,耐心等待上一笔充值结果后再提交!');
            //     }
            //     $is_success_count = CzOrder::where('mobile', $mobile)->where('order_status', 3)->whereBetween('created_at', [$spec_info->limit_time, time()])->count();
            //     if ($is_success_count == $productBlackInfo->limit_num) {
            //         return error('当前手机号被限制充值!');
            //     }
            //     if ($is_handing_count + $is_success_count == $productBlackInfo->limit_num) {
            //         return error('当前手机号被限制充值,且已经提交过,耐心等待上一笔充值结果后再提交!');
            //     }
            // }
        }
        // 获取产品的号码提交次数
        $phoneSubmitMax = $user->phone_max ?? env('PHONE_SUBMIT_MAX') ?? 5;
        // logger('phoneSubmitMax' . $phoneSubmitMax);
        //获取当天手机号下单失败次数 
        $curMobileCount = CzOrder::where([
            "order_status" => 4,
            "mobile" => $mobile,
            "spec_id" => $spec_id
        ])->where('pay_status', 1)->whereBetween('updated_at', [strtotime(date('Y-m-d', time())), time()])->count();
        if ($curMobileCount >= $phoneSubmitMax) {
            return error('当前产品的手机号提交上限,请隔天再试');
        }
        $is_split =  0;

        // 获取充值面值
        $face_value = $spec_info->face_value;
        $hf_type = $product_info->hf_type;


        $product_ids = CzProduct::filter([
            'mobi_province_id' => $province_id,
            'mobi_city_id' => $city_id,
            'isp' => $isp
        ])->where('hf_type', $hf_type)->where('status', 1)->pluck('id');
        $spec_ids = CzSpec::where('face_value', $face_value)->where('status', 1)
            ->whereIn('product_id', $product_ids)->pluck('id');


        if ($user->group_id > 0) {
            //客户分组产品
            $old_user_group_product = UserGroupProduct::where('product_id', $product_id)
                ->where('spec_id', $spec_id)
                ->where('user_group_id', $user->group_id)->first();

            if (!$old_user_group_product) {
                return error('未分配产品');
            }
            $cur_user_group_product_id = $old_user_group_product->id;  //默认不分省
            // 分省市
            if ($product_info->is_split) {
                // 
                $user_group_product = UserGroupProduct::whereIn('product_id', $product_ids)
                    ->whereIn('spec_id', $spec_ids)
                    ->where('user_group_id', $user->group_id)->get();

                $temp_arr = $user_group_product->toArray();
                // 优先匹配分省
                foreach ($temp_arr as $key => $val) {
                    $product_id = $val['product_id'];
                    $prodcut = CzProduct::find($product_id);
                    if ($prodcut->city_id) {
                        // 分市
                        $cur_user_group_product_id = $val['id'];
                        logger('mobile' . $mobile . ',cur_user_group_product_id' . $cur_user_group_product_id . '分市');
                        break;
                    } else if ($prodcut->province_id) {
                        // 分省
                        $cur_user_group_product_id = $val['id'];
                        logger('mobile' . $mobile . ',cur_user_group_product_id' . $cur_user_group_product_id . '分省');
                        break;
                    }
                }
            }
            if ($cur_user_group_product_id != $old_user_group_product->id) {
                $new_user_group_product =  UserGroupProduct::find($cur_user_group_product_id);
                $is_split =  1;
            } else {
                $new_user_group_product = $old_user_group_product;
            }

            //  给用户扣款使用的是不分省市的价格
            $user_price = $old_user_group_product->user_group_price;
            // 其他配置使用的是分省市的配置
            $is_loop = $new_user_group_product->is_loop;
            $submit_order_count = $new_user_group_product->submit_order_count;
            $user_product_timeout = $new_user_group_product->timeout ?? 0;

            // 使用新的产品规格
            if ($new_user_group_product->spec_id != $spec_info->id) {
                $spec_info = CzSpec::find($new_user_group_product->spec_id);
            }
            if ($new_user_group_product->product_id != $product_info->id) {
                $product_info = CzProduct::find($new_user_group_product->product_id);
            }

            $new_title = $product_info->title . $spec_info->face_value;
        } else {
            //客户产品
            $old_user_product = CustomerProduct::where('product_id', $product_id)
                ->where('spec_id', $spec_id)
                ->where('user_id', $user->id)->first();
            if (!$old_user_product) {
                return error('未分配产品');
            }
            logger("old_user_product" . $old_user_product->id);
            // 获取需要查询的面值
            // $face_value = $spec_info->face_value;
            // $hf_type = $product_info->hf_type;

            $cur_user_product_id = $old_user_product->id;
            if ($product_info->is_split) {
                $user_product = CustomerProduct::filter([
                    'user_id' => $user->id,
                    'isp' => $isp
                ])->whereIn('spec_id', $spec_ids)->whereIn('product_id', $product_ids)->orderBy('id', 'desc')->get();
                logger('$user_product' . json_encode($user_product));

                if (!$user_product) {
                    return error('未分配产品');
                }
                $temp_arr = $user_product->toArray();

                // 优先匹配分省
                foreach ($temp_arr as $key => $val) {
                    $product_id = $val['product_id'];
                    $prodcut = CzProduct::find($product_id);
                    if ($prodcut->city_id) {
                        // 分市
                        $cur_user_product_id = $val['id'];
                        logger('mobile' . $mobile . ',cur_user_product_id' . $cur_user_product_id . '分市');
                        break;
                    } else if ($prodcut->province_id) {
                        // 分省
                        $cur_user_product_id = $val['id'];
                        logger('mobile' . $mobile . ',cur_user_product_id' . $cur_user_product_id . '分省');
                        break;
                    }
                }
            }
            if ($old_user_product->id != $cur_user_product_id) {
                $new_user_product = CustomerProduct::find($cur_user_product_id);
                $is_split =  1;
            } else {
                $new_user_product = $old_user_product;
            }
            // 给用户扣款使用的是不分省市的价格
            $user_price = $old_user_product->user_price;
            // 其他配置使用的是分省市的配置
            $is_loop = $new_user_product->is_loop;
            $submit_order_count = $new_user_product->submit_order_count;
            $user_product_timeout = $new_user_product->timeout ?? 0;



            // 使用新的产品规格
            if ($new_user_product->spec_id != $spec_info->id) {
                $spec_info = CzSpec::find($new_user_product->spec_id);
            }
            if ($new_user_product->product_id != $product_info->id) {
                $product_info = CzProduct::find($new_user_product->product_id);
            }
            $new_title = $product_info->title . $spec_info->face_value;
            // var_dump($new_title);
        }
        // logger('submit_order_count' . $submit_order_count);
        $order_data = [
            'order_sn' => 'CZ' . date("YmdH") . sprintf('%04d', $user['id']) . sprintf('%03d', rand(1, 999)) . sprintf('%03d', rand(1, 999)) . sprintf('%03d', rand(1, 999)),
            'product_name' => $product_info->title,
            'mobile' => $mobile,
            'face_value' => $spec_info->face_value,
            'cost' => $user_price,
            'price' => $user_price,
            'area_name' => $mobile_info->province . '-' . $mobile_info->city,
            'province_id' => $province_id,
            'city_id' => $city_id,
            'order_status' => $spec_info->is_cache == 1 ? 5 : 1, //5是压单
            'isp' => $product_info->isp,
            'biz_type' => $product_info->type,
            'hf_type' => $product_info->hf_type,
            'product_id' => $product_info->id,
            'spec_id' => $spec_info->id,
            'is_loop' => $is_loop,
            'submit_from' => 'web' . ($is_split ? "|" . ($old_title . '下分为->' . $new_title) : ""),
            'is_auto' => $spec_info->is_auto,
            'submit_order_count' => $submit_order_count ?? env('ORDER_RE_SUBMIT_LIMIT')
        ];
        //默认客户订单号为 平台订单号

        if ($batch_order_sn) {
            $order_data['batch_order_sn'] = $batch_order_sn;
        }
        if ($user_order_sn) {
            //检查是否重复
            $has_user_order_sn = CzOrder::where('user_order_sn', $user_order_sn)->exists();
            // $has_user_order_sn = CzOrder::where('user_order_sn', $user_order_sn)->select('id')->first();
            if ($has_user_order_sn) {
                return error('订单号已存在');
            }
            $order_data['user_order_sn'] = $user_order_sn;
        } else {
            $order_data['user_order_sn'] = $order_data['order_sn'];
        }
        // 验证手机号
        if ($user->id != 75) {
            $validateRes = $this->validateMobile($mobile);
            if (isset($validateRes['code']) && $validateRes['code'] == 200 && $validateRes['is_trans'] != 0) {
                // 无效号码直接返回
                if (!$validateRes['is_has']) {
                    // 数据库不存在记录在入库
                    // 携号转网入库
                    DB::table('mobile_is_trans')->insert([
                        "mobile" => $mobile,
                        "created_at" => time(),
                        "updated_at" => time(),
                    ]);
                }
                return error('携号转网,无法充值!');
                // DB::table('cz_order')->where('id', $order_id)->update([
                //     "order_status" => 4,
                //     "msg" => "携号转网",
                // ]);
                // $this->callbackOrderForFail($goodsNo, $user_order_sn, $mobile, $barcode, 4);
                // continue;
            }
        }


        $balance_log_data = [
            'order_sn' => $order_data['order_sn'],
            'money' => $user_price,
            'bf_balance' => $user->balance,
            'af_balance' => $user->balance - $user_price,
            'bank' => '',
            'type' => 3,
            'remark' => "{$mobile},充值[{$product_info->title}{$spec_info->face_value}]，消费{$user_price}元",
            'user_id' => $user->id,
        ];

        //如果是快充话费 增加超时
        /*
        if($order_data['biz_type'] == 1 && $order_data['hf_type'] == 1 && $user->kc_timeout > 0){
            $order_data['timeout'] = time() + intval($user->kc_timeout);
        }
        */
        //用户分配产品的超时时间
        if ($user_product_timeout > 0) {
            $order_data['timeout'] = time() + intval($user_product_timeout);
        }
        //获取订单号


        DB::beginTransaction();
        try {
            $is_dec_balance = DB::table('sys_users')
                ->where('id', $user->id)
                ->where('balance', '>=', ($user_price - $user->credit))
                ->decrement('balance', $user_price);
            if (!$is_dec_balance) {
                DB::rollBack();
                return error('余额不足');
            }
            BalanceLog::create($balance_log_data);
            $model = CzOrder::create($order_data);
            DB::commit();
        } catch (QueryException $e) {
            DB::rollBack();
            return error('下单失败:QueryException' . $e->getMessage());
        }
        $order_id = $model->id;

        //自动订单且状态为1就推送去自动处理
        if ($order_data['is_auto'] == 1 && $order_data['order_status'] == 1) {
            sock_queue($order_id, 'queue_order');
        }

        return success(['data' => $model], '下单成功');
    }
    // public function limit()
    // {

    //     return 
    // }

    public function orderList(Request $request)
    {
        $paginator = CzOrder::filter($request->all())->dataFilter()
            ->orderBy('id', 'desc')
            ->where('pay_status', 1)
            ->select('id', 'order_sn', 'mobile', 'product_name', 'face_value', 'biz_type', 'isp', 'price', 'order_status', 'updated_at', 'created_at', 'user_order_sn', 'area_name', "submit_from")
            ->paginate($this->pageSize);
        $result = [
            'rows' => $paginator->items(),
            'total' => $paginator->total(), // 获取结果集中的数据总数
            'last_page' => $paginator->lastPage(),
            'currentPage' => $paginator->currentPage()
        ];
        foreach ($result['rows'] as $key => &$val) {
            $num = stripos($val['submit_from'], "->");

            if ($num) {
                $len = strlen($val['face_value']);
                $str = substr($val['submit_from'], 4, $num - 13 - $len);
                $val['product_name'] = $str;
            } else {
            }
        }
        // $data = page_format($paginator);
        // var_dump($data);
        // return 111;
        return success($result);
    }
    public function validateMobile($mobile)
    {
        // 先从本地数据库验证
        $return_data = [
            "code" => 200,
            "is_trans" => 0,
            "is_has" => 0,
            "area" =>  NULL,
            "isp" =>  NULL,
            "msg" =>  ''
        ];
        $isHas = DB::table('mobile_is_trans')->where('mobile', $mobile)->first();
        if ($isHas) {
            $return_data['is_trans'] = 1;
            $return_data['is_has'] = 1;
            return $return_data;
        }
        $post_data = [
            "apikey" => env('validate_mobile_key'),
            "mobile" => $mobile,
        ];
        $headers = [
            'Content-Type: application/json',
        ];
        // logger('请求借口');
        // var_dump($this->validateMobileUrl);
        $res = $this->httpRequest(env('validateMobileUrl'), "POST", $post_data);
        // return $res;
        $return_arr = json_decode($res, true);
        $return_data['msg'] =  $return_arr['reason'] ?? "";

        if ($return_arr['code'] == 0) {

            if (isset($return_arr['result'])) {
                $return_data['area'] = $return_arr['result']['Area'] ?? "";
                $return_data['isp'] = $return_arr['result']['Init_isp'] ?? "";
            }

            if ($return_arr['result']['res'] == 0) {
                $return_data['is_trans'] = 0;
            } else {
                $return_data['is_trans'] = 1;
            }
        } else {
            // if (isset($return_arr['code'])) {
            //     // 查询异常可正常下单
            //     logger('接口查询异常' . $return_data['msg']);
            // }
            logger('接口查询异常' . $return_data['msg']);
            $return_data['code'] = 200;
            $return_data['is_trans'] = 0;
        }
        return $return_data;
    }
    public function productList(Request $request)
    {
        $params = $request->only(['id', 'type', 'isp', 'mobi_province_id', 'mobi_city_id']);
        $params['status'] = 1;

        //获取用户全部产品
        $user_id = auth()->id();
        $user = SysUser::find($user_id);
        $user_spec_id = [0];
        if ($user->group_id > 0) {
            $params['user_group_id'] = $user->group_id;
            $user_spec_id = UserGroupProduct::filter($params)->pluck('spec_id');
            $user_all_price = UserGroupProduct::filter($params)->select('spec_id', 'user_group_price as user_price')->get();
        } else {
            $params['user_id'] = $user->id;
            $user_spec_id = CustomerProduct::filter($params)->pluck('spec_id');
            $user_all_price = CustomerProduct::filter($params)->select('spec_id', 'user_price')->get();
        }
        if ($user_all_price) {
            $user_all_price = $user_all_price->toArray();
            $user_all_price = convert_arr_key($user_all_price, 'spec_id');
        }
        //        return $user_all_price;
        $params['mobi_spec_id'] = $user_spec_id;
        //获取产品
        $product_list = CzProduct::with([
            'specs' => function ($query) use ($user_spec_id) {
                $query->whereIn('id', $user_spec_id)->select('id', 'product_id', 'face_value', 'market_price', 'spec_code', 'status');
            },
            'province' => function ($query) {
                $query->select('id', 'short_name');
            },
            'city' => function ($query) {
                $query->select('id', 'short_name');
            },
        ])->filter($params)->select('id', 'title', 'type', 'hf_type', 'isp', 'province_id', 'city_id')->get();
        if ($product_list) {
            $product_list = $product_list->toArray();
            foreach ($product_list as $k1 => $product) {
                foreach ($product['specs'] as $k2 => $spec) {
                    $product_list[$k1]['specs'][$k2]['user_price'] = $user_all_price[$spec['id']]['user_price'];
                }
            }
        }
        return success(['data' => $product_list], '获取成功');
    }

    public function getBalanceLog(Request $request)
    {
        $paginator = BalanceLog::filter($request->all())->where('user_id', auth()->id())->select('id', 'order_sn', 'money', 'type', 'remark', 'created_at')->orderBy('id', 'desc')->paginate($this->pageSize);
        return success(page_format($paginator));
    }
    public function getOrderStatus($type)
    {
        $dictData = SysDictData::where('dict_type', 'cz_order_status')->get();
        $dictData = $dictData->toArray();
        $res = '';
        foreach ($dictData as $key => $value) {
            if ($value['dict_value'] == $type) {
                $res = $value['dict_label'];
                break;
            }
        }
        return $res;
    }
    public function exportUserOrder(Request $request)
    {
        $field = "order_sn, product_name, face_value, mobile, price, created_at";
        $fileName = "客户充值订单导出[" . date('YmdHi') . "].csv";
        // 清空输出流，防止有别的信息
        ob_end_clean();
        // 打开一个输出流
        ob_start();
        // 设置header信息
        header("Content-Type: text/csv");
        header("Content-Disposition:filename=" . $fileName);
        header("Access-Control-Allow-Origin: *");

        // 打开文件流
        $fileHandle = fopen('php://output', 'w');
        //转码 防止乱码
        fwrite($fileHandle, chr(0xEF) . chr(0xBB) . chr(0xBF));
        $header_data = [
            '订单号', '客户订单号', '批量订单号', '产品', '面值', '手机号', '价格', '订单状态', '创建时间'
        ];
        if (!empty($header_data)) {
            fputcsv($fileHandle, $header_data);
        }
        // 先把标题写进去
        //        fputcsv($fileHandle, $title);
        $params = $request->all();
        if (isset($request['ids'])) {
            CzOrder::whereIn('id', $request['ids'])->dataFilter()->with([
                'user' => function ($query) {
                    $query->select('id', 'username');
                }
            ])->where('pay_status', 1)->orderBy('id', 'desc')->select(
                'order_sn',
                'user_order_sn',
                'batch_order_sn',
                'product_name',
                'face_value',
                'mobile',
                'price',
                'order_status',
                'created_at'
            )->chunk(10000, function ($items) use ($fileHandle) {
                $arrs = $items->toArray();
                foreach ($arrs as $item) {
                    $status = $this->getOrderStatus($item['order_status']);
                    array_splice($item, 7, 1, $status); //将order_status替代为文本
                    fputcsv($fileHandle, $item);
                }
                //每2000条释放一次资源
                ob_flush();
                flush();
            });
        } else {
            CzOrder::filter($params)->dataFilter()->with([
                'user' => function ($query) {
                    $query->select('id', 'username');
                }
            ])->where('pay_status', 1)->orderBy('id', 'desc')->select(
                'order_sn',
                'user_order_sn',
                'batch_order_sn',
                'product_name',
                'face_value',
                'mobile',
                'price',
                'order_status',
                'created_at'
            )->chunk(10000, function ($items) use ($fileHandle) {
                $arrs = $items->toArray();
                foreach ($arrs as $item) {
                    $status = $this->getOrderStatus($item['order_status']);
                    array_splice($item, 7, 1, $status); //将order_status替代为文本
                    fputcsv($fileHandle, $item);
                }
                //每2000条释放一次资源
                ob_flush();
                flush();
            });
        }

        //释放资源
        ob_flush();
        flush();
        ob_end_clean();
    }

    public function statics(Request $request)
    {
        $params = $request->only(['product_id', 'biz_type', 'isp', 'province_id', 'city_id', 'face_value', 'params']);
        $params['user_id'] = auth()->id();
        $params['pay_status'] = 1;

        $total_info = CzOrder::filter($params)->selectRaw('COUNT(*) AS counts,SUM(price) AS sum_money,SUM(cost) AS sum_cost')->first();
        $total_nums = $total_info->counts ?? 0;
        $total_money = $total_info->sum_money ?? 0;

        $success_info = CzOrder::filter($params)->where('order_status', 3)->selectRaw('COUNT(*) AS counts,SUM(price) AS sum_money,SUM(cost) AS sum_cost')->first();
        $success_nums = $success_info->counts ?? 0;
        $success_money = $success_info->sum_money ?? 0;




        $fail_info = CzOrder::filter($params)->where('order_status', 4)->selectRaw('COUNT(*) AS counts,SUM(price) AS sum_money,SUM(cost) AS sum_cost')->first();
        $fail_nums = $fail_info->counts ?? 0;
        $fail_money = $fail_info->sum_money ?? 0;

        $processing_nums = $total_nums - $success_nums - $fail_nums;
        $processing_money = $total_money - $success_money - $fail_money;

        return success(['data' => [
            'total_nums' => $total_nums,
            'total_money' => $total_money,

            'success_nums' => $success_nums,
            'success_money' => $success_money,

            'processing_nums' => $processing_nums,
            'processing_money' => $processing_money,

            'fail_nums' => $fail_nums,
            'fail_money' => $fail_money,

        ]]);
    }

    public function getUserInfo(Request $request)
    {
        $user = auth()->user();
        $domain = env('APP_URL');
        return success([
            'data' => [
                'id' => $user->id,
                'username' => $user->username,
                'nickname' => $user->nickname,
                'credit' => $user->credit,
                'balance' => $user->balance,
                'apiurl' => $domain . "/api.php",
            ]
        ]);
    }
    public function resetPwd(Request $request)
    {
        $user = SysUser::where('user_type', $this->customer_config_map['customer_type'])->find(auth()->id());
        if (Hash::check($request->post('oldPassword'), $user->password) == false) {
            return error('旧密码不匹配');
        }
        DB::table('sys_users')->where('id', $user->id)->update([
            'password' => Hash::make(trim($request->post('newPassword')))
        ]);
        return success([], '修改成功');
    }

    public function getSecret(Request $request)
    {
        $user = auth()->user();
        if (Hash::check($request->post('password'), $user->password) == false) {
            return error('密码不匹配');
        }
        return success([
            'data' => get_api_secret($user->api_secret)
        ]);
    }
}
